




HTML Id Attribute
The id attribute refers to a unique value for an HTML element. This HTML id value can be used with CSS and JavaScript to perform certain task.
HTML id with CSS
In CSS, if you want to select an element with a specific id, write a hash (#) character, followed by the id of the element.
Example:
Use the HTML id "myid" with CSS:


<style>  

#myid {  

    background-color: lightpink;  

    color: black;  

    padding: 40px;  

    text-align: center;  

}   

</style>  

<h1 id="myid">Example of HTML id</h1>  


Note: Here the id attribute is "myid" which can be used on any HTML element. The HTML id value is case-sensitive and it must contain at least one character, and must not contain whitespace (spaces, tabs, etc.).

Difference between HTML Class and ID
An HTML class name can be used by multiple elements while An HTML element can only have one unique id that belongs to that single element.
Example:


<!DOCTYPE html>  

<html>  

<head>  

<style>  

/* Style the element with the id "myid" */  

#myid {  

    background-color: pink;  

    color: black;  

    padding: 40px;  

    text-align: center;  

}  

  

/* Style all elements with the class name "fruit" */  

.fruit {  

    background-color: orange;  

    color: white;  

    padding: 10px;  

}   

</style>  

</head>  

<body>  

  

<h2>Difference Between Class and ID</h2>  

  

<h1 id="myid">My Favorite Fruits</h1>  

  

<h2 class="fruit">Mango</h2>  

<p>The Kinkg of all fruits.</p>  

  

<h2 class="fruit">Orange</h2>  

<p>Full of Vitamin C</p>  

  

<h2 class="fruit">Apple</h2>  

<p>An apple a day, keeps the doctor away.</p>  

  

</body>  

</html>  




HTML id with JavaScript
You can use HTML id with JavaScript getElementById() method to access an element with a specified id.
Example:


<!DOCTYPE html>  

<html>  

<body>  

<h2>HTML id with JavaScript</h2>  

<h1 id="myid">Hello JavaTpoint!</h1>  

<button onclick="displayResult()">Change text</button>  

<script>  

function displayResult() {  

    document.getElementById("myid").innerHTML = "All the best for future!";  

}  

</script>  

</body>  

</html>  

















Please Share





